"""
LLM提供商工厂
根据配置动态创建不同的LLM提供商实例
"""
from typing import Dict, Any, Optional
from loguru import logger

from storyforge.providers.base import ProviderBase
from storyforge.providers.llm_openai import LLMOpenAIProvider
from storyforge.providers.llm_claude import LLMClaudeProvider
from storyforge.providers.llm_gemini import LLMGeminiProvider
from storyforge.providers.llm_moonshot import LLMMoonshotProvider
from storyforge.providers.llm_tongyi import LLMTongyiProvider
from storyforge.providers.llm_deepseek import LLMDeepSeekProvider
from storyforge.config import get_provider_config


class LLMProviderFactory:
    """LLM提供商工厂"""
    
    # 注册的提供商类型映射
    _provider_classes: Dict[str, type] = {
        "openai": LLMOpenAIProvider,
        "claude": LLMClaudeProvider,
        "gemini": LLMGeminiProvider,
        "moonshot": LLMMoonshotProvider,
        "tongyi": LLMTongyiProvider,
        "deepseek": LLMDeepSeekProvider,
    }
    
    @classmethod
    def register_provider(cls, provider_type: str, provider_class: type):
        """
        注册提供商类
        
        Args:
            provider_type: 提供商类型标识
            provider_class: 提供商类（继承自ProviderBase）
        """
        if not issubclass(provider_class, ProviderBase):
            raise ValueError(f"提供商类必须继承自ProviderBase: {provider_class}")
        cls._provider_classes[provider_type] = provider_class
        logger.info(f"已注册提供商类型: {provider_type}")
    
    @classmethod
    def create_provider(cls, provider_name: str) -> ProviderBase:
        """
        创建提供商实例
        
        Args:
            provider_name: 提供商名称（配置中的key）
            
        Returns:
            ProviderBase实例
            
        Raises:
            ValueError: 提供商配置不存在或类型不支持
        """
        provider_config = get_provider_config(provider_name)
        if not provider_config:
            raise ValueError(f"提供商配置不存在: {provider_name}")
        
        config_dict = provider_config.dict(exclude_none=True)
        
        # 确定提供商类型
        provider_type = config_dict.get("type", "llm")
        
        # 如果type是llm或不在已注册的类型中，尝试从provider_name推断
        if provider_type == "llm" or provider_type not in cls._provider_classes:
            # 根据provider_name推断类型
            if "openai" in provider_name.lower():
                provider_type = "openai"
            elif "claude" in provider_name.lower() or "anthropic" in provider_name.lower():
                provider_type = "claude"
            elif "gemini" in provider_name.lower() or "google" in provider_name.lower():
                provider_type = "gemini"
            elif "moonshot" in provider_name.lower():
                provider_type = "moonshot"
            elif "tongyi" in provider_name.lower() or "qwen" in provider_name.lower():
                provider_type = "tongyi"
            elif "deepseek" in provider_name.lower():
                provider_type = "deepseek"
            else:
                provider_type = "openai"  # 默认使用OpenAI
        
        # 获取提供商类
        provider_class = cls._provider_classes.get(provider_type)
        if not provider_class:
            # 如果未找到，尝试使用openai作为默认
            logger.warning(f"未找到提供商类型 {provider_type}，使用OpenAI作为默认")
            provider_class = LLMOpenAIProvider
        
        try:
            # 创建实例
            instance = provider_class(config_dict)
            logger.debug(f"已创建提供商实例: {provider_name} ({provider_type})")
            return instance
        except Exception as e:
            logger.error(f"创建提供商实例失败: {provider_name}, 错误: {e}")
            raise ValueError(f"创建提供商实例失败: {provider_name}, 错误: {e}")
    
    @classmethod
    def get_supported_providers(cls) -> list:
        """
        获取支持的提供商类型列表
        
        Returns:
            支持的提供商类型列表
        """
        return list(cls._provider_classes.keys())

